package vn.bang.xiangqi.components;

import java.util.Collection;

import vn.bang.xiangqi.infrastructure.Position;
import vn.bang.xiangqi.infrastructure.Vector;
import vn.bang.xiangqi.utility.BoardUtil;

public class Cannon extends AbstractBaseNode {
	public Cannon() {
		super();
	}

	public Cannon(Position originalPosition) {
		super(originalPosition);
	}

	@Override
	protected boolean notPrevented(Vector vector, Collection<INode> ours,
			Collection<INode> enemies) {
		int blockCount = 0;

		for (INode node : ours) {
			blockCount += (true == between(node.GetCurrentPosition(), vector) ? 1
					: 0);
		}
		for (INode enemy : enemies) {
			blockCount += (true == between(enemy.GetCurrentPosition(), vector) ? 1
					: 0);
		}

		if (1 < blockCount) {
			return false;
		} else {
			if (hasNodeBetween(vector, ours, enemies)) {
				Position destinationPosition = new Position(
						position.getColumnIndex() + vector.getColumn(),
						position.getRowIndex() + vector.getRow());
				INode enemyNeedKilled = retrieveNodeAtPosition(
						destinationPosition, enemies);

				if (null == enemyNeedKilled) {
					return false;
				}
			} else {
				return true;
			}
		}

		return true;
	}

	@Override
	protected Vector retrieveVectorMovingTo(Position destinationPosition) {
		if (null == destinationPosition
				|| !BoardUtil.IsInBoard(destinationPosition)) {
			return null;
		}

		Vector vector = null;

		if (position.getColumnIndex() == destinationPosition.getColumnIndex()) {
			vector = new Vector(0, destinationPosition.getRowIndex()
					- position.getRowIndex());
		}

		if (position.getRowIndex() == destinationPosition.getRowIndex()) {
			vector = new Vector(destinationPosition.getColumnIndex()
					- position.getColumnIndex(), 0);
		}

		return vector;
	}
}